package com.soriya.nestlive.util;

import com.soriya.nestlive.constant.CommonConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public final class RedisUtil {

    private static RedisTemplate<String, Object> redisTemplate;

    private static final String prefix = CommonConst.REDIS_KEY_PREFIX;

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        RedisUtil.redisTemplate = redisTemplate;
    }

    public static  <T> void set(String key, T value) {
        set(key, value, -1);
    }

    public static <T> void set(String key, T value, long timeout) {
        set(key, value, timeout, TimeUnit.SECONDS);
    }

    public static <T> void set(String key, T value, long timeout, TimeUnit timeUnit) {
        baseSet(key, value, timeout, timeUnit);
    }

    private static <T> void baseSet(String key, T value, long timeout, TimeUnit timeUnit) {
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        operations.set(prefix + key, value, timeout, timeUnit);
    }

    public static <T> T get(String key) {
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        return (T) operations.get(prefix + key);
    }

    public static void expire(String key, long timeout) {
        expire(key, timeout, TimeUnit.SECONDS);
    }

    public static void expire(String key, long timeout, TimeUnit timeUnit) {
        redisTemplate.expire(prefix + key, timeout, timeUnit);
    }

    public static long ttl(String key) {
        Long expire = redisTemplate.getExpire(prefix + key);
        return expire == null ? -1 : expire;
    }

    public static void delete(String key) {
        redisTemplate.delete(prefix + key);
    }
}
